import os
import sys
import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog, messagebox
from urllib.request import urlopen
from pathlib import Path
import re
from plugin_manager import PluginManager
from language_manager import LanguageManager
from resource_downloader import ResourceDownloader
from windows import PluginManagerWindow
from language_plugin import LanguagePlugin

class WSCatcher:
    """WSCatcher v3.0 - 增强版网页内容捕获与编辑器"""
    def __init__(self):
        self.window = tk.Tk()

        # 颜色
        self.highlight_colors = {
            'tag': 'blue',
            'attr': 'green',
            'value': 'red',
            'comment': 'gray',
            'doctype': 'purple'
        }

        # 创建插件管理器
        self.plugin_dir = "plugins"
        self.plugin_manager = PluginManager()
        self.plugin_manager.load_plugins(self.plugin_dir)

        # 初始化插件
        self.plugin_manager.initialize_plugins(self)

        # 获取语言插件和语言管理器
        self.language_plugin = next((p for p in self.plugin_manager.plugins if isinstance(p, LanguagePlugin)), None)
        self.language_manager = self.language_plugin.language_manager if self.language_plugin else None

        # 设置应用标题
        app_title = self.language_manager.get_text("app_title", "WSCatcher v3.0") if self.language_manager else "WSCatcher v3.0"
        self.window.title(app_title)
        self.window.geometry("1200x800")

        # 创建UI组件
        self._create_widgets()
        self._create_menu()
        self._create_status_bar()
        self._setup_highlight()

        # 通知插件UI已就绪
        self.plugin_manager.on_ui_ready()

        # 窗口关闭时检查语言是否更改
        self.window.protocol("WM_DELETE_WINDOW", self._on_close)

        self.window.mainloop()

    def _create_menu(self):
        """创建菜单栏"""
        menubar = tk.Menu(self.window)

        # File 菜单
        self.file_menu = tk.Menu(menubar, tearoff=0)

        # 使用语言管理器获取本地化文本
        open_webpage_text = self.language_manager.get_text("menu.open_webpage", "打开网页 (Ctrl+O)") if self.language_manager else "打开网页 (Ctrl+O)"
        save_text = self.language_manager.get_text("menu.save", "保存 (Ctrl+S)") if self.language_manager else "保存 (Ctrl+S)"
        clear_text = "清空编辑器 (Ctrl+E)"  # 固定文本，由插件添加
        
        self.file_menu.add_command(label=open_webpage_text, command=self.load_url)
        self.file_menu.add_command(label=save_text, command=self.save_file)
        self.file_menu.add_separator()
        
        # 清空编辑器命令（由插件添加）
        self.clear_editor = lambda: self.editor.delete('1.0', tk.END)

        self.window.bind("<Control-e>", lambda e: self.clear_editor())

        self.window.bind("<Control-E>", lambda e: self.clear_editor())

        self.file_menu.add_command(label=clear_text, command=self.clear_editor)

        file_text = self.language_manager.get_text("menu.file", "File") if self.language_manager else "File"
        menubar.add_cascade(label=file_text, menu=self.file_menu)

        # Run 菜单
        self.run_menu = tk.Menu(menubar, tearoff=0)

        # 使用语言管理器获取本地化文本
        run_html_text = self.language_manager.get_text("menu.run_html", "运行 (Ctrl+R)") if self.language_manager else "运行 (Ctrl+R)"

        self.run_menu.add_command(label=run_html_text, command=self.run_html)

        run_text = self.language_manager.get_text("menu.run", "Run") if self.language_manager else "Run"
        menubar.add_cascade(label=run_text, menu=self.run_menu)

        # Plugins 菜单
        self.plugins_menu = tk.Menu(menubar, tearoff=0)

        # 使用语言管理器获取本地化文本
        plugin_options_text = self.language_manager.get_text("menu.plugin_options", "插件选项") if self.language_manager else "插件选项"

        self.plugins_menu.add_command(label=plugin_options_text, command=self._open_plugin_manager)

        plugins_text = self.language_manager.get_text("menu.plugins", "Plugins") if self.language_manager else "Plugins"
        menubar.add_cascade(label=plugins_text, menu=self.plugins_menu)

        self.window.config(menu=menubar)

    def _create_status_bar(self):
        """创建状态栏"""
        self.status_bar = ttk.Frame(self.window, height=25)
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

        # 左侧：当前操作和进度
        ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
        self.operation_label = ttk.Label(self.status_bar, text=ready_text, anchor=tk.W)
        self.operation_label.pack(side=tk.LEFT, padx=5, pady=2)

        # 右侧：Ln,Col
        self.position_label = ttk.Label(self.status_bar, text="Ln 1, Col 0", anchor=tk.E)
        self.position_label.pack(side=tk.RIGHT, padx=5, pady=2)

    def load_url(self):
        url = self.url_entry.get()

        # 使用语言管理器获取本地化文本
        loading_text = self.language_manager.get_text("status_bar.loading", "正在加载网页...") if self.language_manager else "正在加载网页..."
        self.operation_label.config(text=loading_text)

        try:
            with urlopen(url) as response:
                html_content = response.read().decode('utf-8')
            self.editor.delete('1.0', tk.END)
            self.editor.insert(tk.END, html_content)

            # 使用语言管理器获取本地化文本
            ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
            self.operation_label.config(text=ready_text)
        except Exception as e:
            # 使用语言管理器获取本地化文本
            load_failed_text = self.language_manager.get_text("messages.load_failed", "加载失败") if self.language_manager else "加载失败"
            messagebox.showerror(load_failed_text, str(e))

            # 使用语言管理器获取本地化文本
            ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
            self.operation_label.config(text=ready_text)

    def save_file(self):
        """保存文件并处理资源下载"""
        # 使用语言管理器获取本地化文本
        saving_text = self.language_manager.get_text("status_bar.saving", "正在保存文件...") if self.language_manager else "正在保存文件..."
        self.operation_label.config(text=saving_text)

        filename = filedialog.asksaveasfilename(
            defaultextension=".html",
            filetypes=[("HTML文件", "*.html"), ("所有文件", "*.*")]
        )
        if filename:
            try:
                base_url = self.url_entry.get()
                html_content = self.editor.get('1.0', tk.END)

                downloader = ResourceDownloader(base_url, html_content, self._update_status_bar)
                modified_html = downloader.process_resources()

                with open(filename, 'w', encoding='utf-8') as f:
                    f.write(modified_html)

                # 使用语言管理器获取本地化文本
                save_success_text = self.language_manager.get_text("messages.save_success", "保存成功") if self.language_manager else "保存成功"
                save_success_message_text = self.language_manager.get_text("messages.save_success_message", "文件已保存到: {path}") if self.language_manager else "文件已保存到: {path}"
                save_success_message_text = save_success_message_text.format(path=filename)

                messagebox.showinfo(save_success_text, save_success_message_text)

                # 使用语言管理器获取本地化文本
                ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
                self.operation_label.config(text=ready_text)
            except Exception as e:
                # 使用语言管理器获取本地化文本
                save_failed_text = self.language_manager.get_text("messages.save_failed", "保存失败") if self.language_manager else "保存失败"
                messagebox.showerror(save_failed_text, str(e))

                # 使用语言管理器获取本地化文本
                ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
                self.operation_label.config(text=ready_text)
        else:
            # 使用语言管理器获取本地化文本
            ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
            self.operation_label.config(text=ready_text)

    def run_html(self):
        # 使用语言管理器获取本地化文本
        running_text = self.language_manager.get_text("status_bar.running", "正在运行...") if self.language_manager else "正在运行..."
        self.operation_label.config(text=running_text)

        try:
            # 获取编辑器中的 HTML 内容
            html_content = self.editor.get('1.0', tk.END)

            # 创建临时文件
            with open("temp.html", 'w', encoding='utf-8') as temp_file:
                temp_file.write(html_content)
            temp_file_path = os.path.abspath("temp.html")

            # 在默认浏览器中打开临时文件
            import webbrowser
            webbrowser.open_new_tab('file://' + temp_file_path)

            # 使用语言管理器获取本地化文本
            ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
            self.operation_label.config(text=ready_text)
        except Exception as e:
            # 使用语言管理器获取本地化文本
            run_failed_text = self.language_manager.get_text("messages.run_failed", "运行失败") if self.language_manager else "运行失败"
            messagebox.showerror(run_failed_text, str(e))

            # 使用语言管理器获取本地化文本
            ready_text = self.language_manager.get_text("status_bar.ready", "就绪") if self.language_manager else "就绪"
            self.operation_label.config(text=ready_text)

    def _on_close(self):
        """窗口关闭处理"""
        # 检查语言插件是否有更改
        if self.language_plugin and self.language_plugin.language_changed:
            # 使用语言管理器获取本地化文本
            restart_required_text = self.language_manager.get_text("messages.restart_required", "需要重启") if self.language_manager else "需要重启"
            language_changed_text = self.language_manager.get_text("messages.language_changed", "语言设置已更改。重启应用程序以应用更改。是否立即重启？") if self.language_manager else "语言设置已更改。重启应用程序以应用更改。是否立即重启？"

            response = messagebox.askyesno(
                restart_required_text, 
                language_changed_text,
                parent=self.window
            )
            if response:
                self._restart_application()
            else:
                self.window.destroy()
        else:
            self.window.destroy()

    def clear_editor(self):
        """清除编辑器内容"""
        self.editor.delete('1.0', tk.END)

    def _create_widgets(self):
        """创建UI组件"""
        self.url_entry = tk.Entry(self.window)
        self.url_entry.pack(fill=tk.X, padx=10, pady=5)
        self.editor = scrolledtext.ScrolledText(self.window)
        self.editor.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 事件绑定
        self.editor.bind('<KeyRelease>', self._schedule_highlight)
        self.editor.bind('<Motion>', self._update_cursor_position)

    def _update_cursor_position(self, event):
        """更新光标位置显示"""
        pos = self.editor.index(tk.INSERT)
        line, column = pos.split('.')
        self.position_label.config(text=f"Ln {line}, Col {column}")

    def _setup_highlight(self):
        """设置语法高亮"""
        for tag, color in self.highlight_colors.items():
            self.editor.tag_configure(tag, foreground=color)

        self.highlight_rules = [
            (r'<!--.*?-->', 'comment'),
            (r'<!DOCTYPE.*?>', 'doctype'),
            (r'<\/?\w+', 'tag'),
            (r'\b\w+=', 'attr'),
            (r'".*?"', 'value'),
            (r"'.*?'", 'value')
        ]

    def _schedule_highlight(self, event=None):
        """延迟高亮"""
        if hasattr(self, 'highlight_id'):
            self.window.after_cancel(self.highlight_id)
        self.highlight_id = self.window.after(500, self._do_highlight)

    def _do_highlight(self):
        """执行语法高亮"""
        start = "1.0"
        end = tk.END
        text = self.editor.get(start, end)
        self.editor.tag_remove("comment", start, end)
        self.editor.tag_remove("doctype", start, end)
        self.editor.tag_remove("tag", start, end)
        self.editor.tag_remove("attr", start, end)
        self.editor.tag_remove("value", start, end)

        for pattern, tag in self.highlight_rules:
            for match in re.finditer(pattern, text):
                start_index = self.editor.index(f"{start} + {match.start()} chars")
                end_index = self.editor.index(f"{start} + {match.end()} chars")
                self.editor.tag_add(tag, start_index, end_index)

    def _open_plugin_manager(self):
        """打开插件管理窗口"""
        PluginManagerWindow(self.window, self.plugin_dir, self._restart_application)

    def _restart_application(self):
        """重启应用程序"""
        python = sys.executable
        os.execl(python, python, *sys.argv)

    def _update_status_bar(self, message):
        self.operation_label.config(text=message)


if __name__ == "__main__":
    WSCatcher()
